package com.das.mechanic_base.mvp.view.create;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.main.X3LicenseNumberAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.bean.live.LiveSelectCarBean;
import com.das.mechanic_base.bean.main.CarDriLicBean;
import com.das.mechanic_base.bean.main.CarMemberBean;
import com.das.mechanic_base.bean.main.CarModelSelectBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.CarPoolBean;
import com.das.mechanic_base.bean.main.CarPoolMainBean;
import com.das.mechanic_base.bean.main.CarSelectBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.UpadateReceBean;
import com.das.mechanic_base.bean.main.ValidCarBean;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.mvp.contract.create.X3CreateServiceContract;
import com.das.mechanic_base.mvp.presenter.create.X3CreateServicePresenter;
import com.das.mechanic_base.mvp.view.camera.X3HomeCameraActivity;
import com.das.mechanic_base.utils.SoftKeyboardStateHelper;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.SpaceFilter;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3KeyboardUtil;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3BottomHomeCarDialog;
import com.das.mechanic_base.widget.X3CarPoolDailog;
import com.das.mechanic_base.widget.X3ModifyHeaderView;
import com.das.mechanic_base.widget.X3PickUpListDialog;
import com.das.mechanic_base.widget.X3SelectCarPopuWindow;
import com.das.mechanic_base.widget.X3TipsDialog;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.das.mechanic_base.app.X3Constent.CODE_CAMERA_REQUEST;
import static com.das.mechanic_base.app.X3Constent.CODE_CAMERA_VIN_REQUEST;

@Route(path = X3AppRouterConstants.Router.CREATE_SERVICE)
public class X3CreateServiceActivity extends X3BaseActivity<X3CreateServicePresenter> implements View.OnClickListener, TextWatcher, X3SelectCarPopuWindow.OnAdapterItemClick, X3LicenseNumberAdapter.ItemOnclick, X3CreateServiceContract.View, X3BottomHomeCarDialog.IOnClickCar {

    @BindView(R2.id.et_car_num)
    EditText et_car_num;
    @BindView(R2.id.rl_load)
    RelativeLayout rl_load;
    @BindView(R2.id.tv_notice)
    TextView tv_notice;
    @BindView(R2.id.btn_creat)
    Button btn_creat;
    @BindView(R2.id.tv_cancel)
    TextView tv_cancel;
    @BindView(R2.id.iv_check)
    ImageView iv_check;
    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.v_bg)
    View v_bg;
    @BindView(R2.id.tv_clear)
    TextView tv_clear;
    @BindView(R2.id.rl_content)
    RelativeLayout rl_content;
    @BindView(R2.id.tv_check)
    TextView tv_check;
    @BindView(R2.id.rl_car)
    RelativeLayout rl_car;
    @BindView(R2.id.sl_view)
    RelativeLayout sl_view;
    @BindView(R2.id.iv_take)
    ImageView iv_take;
    @BindView(R2.id.tv_recent)
    TextView tv_recent;
    @BindView(R2.id.tv_search)
    TextView tv_search;
    @BindView(R2.id.ll_recent)
    LinearLayout ll_recent;
    @BindView(R2.id.rlv_number)
    RecyclerView rlv_number;
    @BindView(R2.id.v_bottom)
    View v_bottom;

    private ValidCarBean numBean;
    private PopupWindow keyPop;

    /**
     * 判断下方按钮的状态
     * 0： 需要跳转到另外两个弹框完善车辆与车主信息 才可以创建接车单
     * 1： 正常 直接创建接车单
     * 2： 有未支付订单 需要跳转到未支付订单
     * 3： 车辆不是首次到店，并且已经填写了车辆信息，到下一级页面需要将车辆信息带过去
     */
    private int status = 0;

    private long carId;
    private long carOwnid;
    private X3SelectCarPopuWindow carPopuWindow;
    private long receiveBaseId;
    private String km;
    private Drawable noPayDrawable;
    private String money_code;
    private X3LicenseNumberAdapter licenseNumberAdapter;
    private String mobile;
    private CarPoolBean selectCarPoolBean;
    private List<LiveSelectCarBean> dataList;
    private X3KeyboardUtil keyboardUtil;
    private X3CarPoolDailog carPoolDailog;
    private String carNum;
    private X3BottomHomeCarDialog homeCarDialog;
    private String lastname;
    private boolean detectionFirstOrNot;

    private CarSelectBean selectBean;
    private boolean isSdk;
    private X3TipsDialog shareDialog;

    //是否是行驶证
    private boolean isDrivingLicense = false;

    //行驶证识别后的对象
    private CarDriLicBean carDriLicBean;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.activity_create_service;
    }

    @Override
    public boolean isTransparent() {
        return true;
    }

    @Override
    protected X3CreateServicePresenter createPresenter() {
        return new X3CreateServicePresenter();
    }

    @Override
    protected void initView() {
        if (android.os.Build.VERSION.SDK_INT != android.os.Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        X3StatusBarUtil.darkMode(this);
        isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rlv_number.setLayoutManager(gridLayoutManager);
        licenseNumberAdapter = new X3LicenseNumberAdapter(this);
        rlv_number.setAdapter(licenseNumberAdapter);
        licenseNumberAdapter.setOnitemClick(this);
        mobile = (String) SpHelper.getData("mobile", "");
        tv_check.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        iv_check.setOnClickListener(this);
        iv_take.setOnClickListener(this);
        btn_creat.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        rl_car.setOnClickListener(this);
        rl_header.setOnClickListener(this);
        et_car_num.addTextChangedListener(this);
        et_car_num.setOnClickListener(this);

        et_car_num.setFilters(new InputFilter[]{new SpaceFilter()});

        noPayDrawable = ContextCompat.getDrawable(this,R.mipmap.x3_car_num_not_paid);
        noPayDrawable.setBounds(0, 0, noPayDrawable.getMinimumWidth(), noPayDrawable.getMinimumHeight());

        if (X3Constent.isChina()) {
            initKeyView();
        }
        clearData();
        mHandler.postDelayed(runnable,200);

//        keyBoardParams();

    }
    Handler keyBoardHandler = new Handler();
    //键盘高度参数
    private void keyBoardParams(){
        SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(this.getWindow().getDecorView());
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                adjustBottomViewParams(keyboardHeightInPx-X3StatusBarUtil.getStatusBarHeight(X3CreateServiceActivity.this) + X3ScreenUtils.dip2px(5,X3CreateServiceActivity.this));
            }

            @Override
            public void onSoftKeyboardClosed() {
                keyBoardHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adjustBottomViewParams(X3ScreenUtils.dip2px(8,X3CreateServiceActivity.this));
                    }
                },X3Constent.getKeyBoardDelayed());
            }
        });
    }

    private void adjustBottomViewParams(int pxH){
        if (v_bottom != null){
            try {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) v_bottom.getLayoutParams();
                layoutParams.height =  pxH;
                layoutParams.width = 1;
                v_bottom.setLayoutParams(layoutParams);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取状态栏高度
     * @return
     */
    public int getStatusBarHeight() {
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public void initData() {
        //数据库查询最近搜索的车牌
        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
        if(carMemberBean == null){
            tv_recent.setVisibility(View.GONE);
        }else {
            if(X3StringUtils.isListEmpty(carMemberBean.getList())){
                tv_recent.setVisibility(View.GONE);
            }else {
                ll_recent.setVisibility(View.VISIBLE);
                tv_search.setVisibility(View.VISIBLE);
                tv_recent.setVisibility(View.VISIBLE);
                rlv_number.setVisibility(View.VISIBLE);
                licenseNumberAdapter.setData(carMemberBean.getList());
            }
        }
    }

    private void initKeyView() {
        View view = View.inflate(this, R.layout.x3_keyboard_pop, null);
        KeyboardView keyView = view.findViewById(R.id.keyboard_view);
        keyPop = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        keyPop.setFocusable(false);
        keyPop.setBackgroundDrawable(null);
        keyPop.setOutsideTouchable(true);
        keyboardUtil = new X3KeyboardUtil(this, keyView, et_car_num);
        keyboardUtil.hideSoftInputMethod();
        keyPop.setOnDismissListener(() -> {
            if (keyboardUtil != null) {
                keyboardUtil.hideSoftInputMethod();
                keyboardUtil.hideKeyboard();
                mHandler.postDelayed(runnable2,250);
            }
        });
    }

   private void  adjustBottom(){
        adjustBottomViewParams(X3ScreenUtils.dip2px(8,X3CreateServiceActivity.this));
    }

    public void showWorkInput() {
        et_car_num.setFocusable(true);
        et_car_num.setFocusableInTouchMode(true);
        et_car_num.requestFocus();
        if (X3Constent.isChina()) {
            et_car_num.performClick();
        }else {
            X3Utils.showInput(et_car_num,this);
        }
    }

    private void clearData() {
        et_car_num.setText("");
        rl_content.setVisibility(View.GONE);
        btn_creat.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_alone_point_bg));
        btn_creat.setEnabled(false);
        tv_clear.setVisibility(View.GONE);
        requestCameraList();
    }

    /**
     * 请求摄像头捕获的车牌号
     */
    private void requestCameraList() {
        Log.e("SSSS","请求摄像头捕获");
        NetWorkHttp.getApi().listTyreDetectionCarNum()
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)this).bindToLife())
                .subscribe(new HttpCallBack<List<LiveSelectCarBean>>() {
                    @Override
                    protected void onDone(List<LiveSelectCarBean> mList) {
                        if (X3StringUtils.isListEmpty(mList)) {
                            initData();
                            return;
                        }
                        tv_recent.setText(getString(R.string.x3_camera_car_num));
                        dataList = mList;
                        //刷新数据
                        if(licenseNumberAdapter == null){
                            return;
                        }
                        ll_recent.setVisibility(View.VISIBLE);
                        licenseNumberAdapter.setData(dataList);
                        rlv_number.setVisibility(View.VISIBLE);
                        tv_recent.setVisibility(View.VISIBLE);
                        tv_search.setVisibility(View.GONE);

                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    @OnClick({R2.id.tv_check,R2.id.iv_take,R2.id.btn_creat,R2.id.tv_cancel,R2.id.rl_header,R2.id.rl_car,
            R2.id.tv_clear,R2.id.iv_check,R2.id.et_car_num,R2.id.tv_search})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_check) {
            if (!X3Utils.isFastClick()) {
                return;
            }
            startToNotFinishReceive(receiveBaseId);
            finish();
            overridePendingTransition(0, R.anim.activity_exit);


        } else if (id == R.id.iv_take) {// 调用拍照
            clearData();
            iOnClikCamera();

        } else if (id == R.id.btn_creat) {
            if (!X3Utils.isFastClick()) {
                return;
            }
            saveCarToDao();
            if (mPresenter != null) {
                mPresenter.searchByCarNum(et_car_num.getText().toString());
            }
        } else if (id == R.id.tv_cancel) {
            finish();
            overridePendingTransition(0, R.anim.activity_exit);

        } else if (id == R.id.rl_header) {
            iOnClickHeader(carOwnid);

        } else if (id == R.id.rl_car) {
            iOnClickCar(carId);

        } else if (id == R.id.tv_clear) {
            /**
             * 清空
             */
            clearData();
        } else if (id == R.id.iv_check) {
            if (carPopuWindow != null) {
                carPopuWindow.showPopu(iv_check);
                v_bg.setVisibility(View.VISIBLE);
            }
        } else if (id == R.id.et_car_num) {
            if (X3Constent.isChina()) {
                if (!keyPop.isShowing()) {
                    String s = et_car_num.getText().toString();
                    if (!X3StringUtils.isEmpty(s) && s.length() >= 1) {
                        // 已经输入了省代码
                        keyboardUtil.changeKeyboard(true);
                    } else {
                        keyboardUtil.changeKeyboard(false);
                    }
                    keyPop.showAtLocation(sl_view, Gravity.BOTTOM, 0, 0);
                    keyboardUtil.showKeyboard();
                    chinaKeyBoard();
                } else {
                    keyPop.dismiss();
                }
            }
        } else if (id == R.id.tv_search) {
            carPoolDailog = new X3CarPoolDailog(this);
            carPoolDailog.show();
            carPoolDailog.setOnItemClick(carPoolBean -> {
                carPoolDailog.dismiss();
                selectCarPoolBean = carPoolBean;
                et_car_num.setText(carPoolBean.label);
                et_car_num.setSelection(carPoolBean.label.length());
                btn_creat.performClick();

            });
            //车辆池
            if (mPresenter != null) {
                mPresenter.listStoreAllCarNum();
            }
        }
    }

    private void chinaKeyBoard(){
        float per = 0.35f;

        if (X3ScreenUtils.getScreenHeight(this) > 1600 && X3ScreenUtils.getScreenHeight(this) <= 1920) {
            per = 0.38f;
        } else if (X3ScreenUtils.getScreenHeight(this) < 1600 && X3ScreenUtils.getScreenWidth(this) <= 720) {
            per = 0.41f;
        } else if (X3ScreenUtils.getScreenWidth(this) == 1080 &&
                (X3ScreenUtils.getScreenHeight(this) >= 2000 && X3ScreenUtils.getScreenHeight(this) <= 2050 )){
            per = 0.35f;
        } else if (X3ScreenUtils.getScreenWidth(this) <= 1080 && X3ScreenUtils.getScreenHeight(this) <= 2300){
            per = 0.42f;
        }

        int h = (int) (X3ScreenUtils.getScreenHeight(this) * per);
        adjustBottomViewParams(h);

    }

    private void saveCarToDao() {
        if (numBean == null) {
            numBean = new ValidCarBean();
        }
        if (selectCarPoolBean == null) {//null代表手动输入的  不为null则是点击获取的
            selectCarPoolBean = new CarPoolBean();
            selectCarPoolBean.label = et_car_num.getText().toString();
            selectCarPoolBean.kwParam = new CarPoolBean.KwParamBean();
            selectCarPoolBean.kwParam.carBrandImgUrl = "";
            if (!X3StringUtils.isListEmpty(dataList)) {
                for (int i = 0; i < dataList.size(); i++) {
                    if (selectCarPoolBean.label.equals(dataList.get(i).num.replaceAll("<em>", "").replaceAll("</em>", ""))) {
                        selectCarPoolBean.kwParam.carBrandImgUrl = dataList.get(i).carBrandImgUrl;
                    }
                }
            }
        }
        //车牌号存储到数据库
        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean(mobile + "车牌号");
        if (carMemberBean == null) {
            carMemberBean = new CarMemberBean();
            List<LiveSelectCarBean> list = new ArrayList<>();
            LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
            liveSelectCarBean.carBrandImgUrl = selectCarPoolBean.kwParam.carBrandImgUrl;
            liveSelectCarBean.num = selectCarPoolBean.label;
            list.add(liveSelectCarBean);
            carMemberBean.setList(list);
            carMemberBean.setCarName(mobile + "车牌号");
            DaoSessionUtils.getInstance().insertCarMemberBean(carMemberBean);
        } else {
            List<LiveSelectCarBean> list = carMemberBean.getList();
            if (X3StringUtils.isListEmpty(list)) {
                list = new ArrayList<>();
            }
            boolean isEqual = false;
            for (LiveSelectCarBean liveSelectCarBean : list) {
                if (!liveSelectCarBean.num.equals(selectCarPoolBean.label)) {
                    continue;
                }
                isEqual = true;
                break;
            }
            if (!isEqual) {
                if (list.size() >= 6) {
                    Collections.reverse(list);
                    list.remove(0);
                    LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
                    liveSelectCarBean.carBrandImgUrl = selectCarPoolBean.kwParam.carBrandImgUrl;
                    liveSelectCarBean.num = selectCarPoolBean.label;
                    carMemberBean.setCarName(mobile + "车牌号");
                    list.add(liveSelectCarBean);
                    Collections.reverse(list);
                    carMemberBean.setList(list);
                    DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                } else {
                    LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
                    liveSelectCarBean.carBrandImgUrl = selectCarPoolBean.kwParam.carBrandImgUrl;
                    liveSelectCarBean.num = selectCarPoolBean.label;
                    carMemberBean.setCarName(mobile + "车牌号");
                    Collections.reverse(list);
                    list.add(liveSelectCarBean);
                    Collections.reverse(list);
                    carMemberBean.setList(list);
                    DaoSessionUtils.getInstance().insertCarMemberBean(carMemberBean);
                }
            } else {//车牌号相同时 更新图标
                if (!X3StringUtils.isListEmpty(dataList)) {
                    for (int i = 0; i < list.size(); i++) {
                        if (X3StringUtils.isEmpty(list.get(i).carBrandImgUrl)) {
                            list.get(i).carBrandImgUrl = selectCarPoolBean.kwParam.carBrandImgUrl;
                            carMemberBean.setList(list);
                            carMemberBean.setCarName(mobile + "车牌号");
                            DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                        }
                    }
                }

            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (charSequence == null) {
            return;
        }
        if (charSequence.toString().contains(" ")) {
            String[] str = charSequence.toString().split(" ");
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < str.length; j++) {
                sb.append(str[j]);
            }
            if (!X3StringUtils.isEmpty(sb.toString())) {
                et_car_num.setText(sb.toString());
                et_car_num.setSelection(sb.length());
            }
        }
    }

    private Pattern pattern = Pattern.compile(".*[a-z]+.*");

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable == null) {
            return;
        }
        //去除空格
        String carNum = editable.toString().replaceAll(" ", "");

        if (X3StringUtils.isEmpty(carNum)) {
            rl_content.setVisibility(View.GONE);
            btn_creat.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_alone_point_bg));
            btn_creat.setEnabled(false);
            tv_clear.setVisibility(View.GONE);
            return;
        }
        tv_clear.setVisibility(View.VISIBLE);
        tv_notice.setText("");
        btn_creat.setBackground(ContextCompat.getDrawable(this,R.drawable.x3_alone_dialog_affirm2));
        btn_creat.setEnabled(true);

        //转大写
        String newCarNum = carNum.toUpperCase();
        Matcher matcher = pattern.matcher(carNum);
        if (matcher.matches()) {
            et_car_num.setText(newCarNum);
            et_car_num.setSelection(newCarNum.length());
        }

        // 搜索车牌号
        if(selectCarPoolBean != null){
            return;
        }
        if(carNum.length() >= 2){
            HashMap<String,Object> map = new HashMap<>();

            if(!X3StringUtils.isEmpty(carNum)){
                map.put("keyword",carNum);
            }
            if (mPresenter != null) {
                mPresenter.getStoreCarNumReceive(map);
            }
        }else {
            requestCameraList();
        }
    }

    @Override
    public void onAdapterClick(String carNum) {
        if (!X3StringUtils.isEmpty(carNum)) {
            et_car_num.setText(carNum);
            et_car_num.setSelection(carNum.length());
        }
    }

    public void setReceiveId(long receiveId) {
        this.receiveBaseId = receiveId;
    }

    @Override
    public void onItemClick(String carNum,String imgUrl) {//搜索点击
        selectCarPoolBean = new CarPoolBean();
        selectCarPoolBean.label = carNum;
        selectCarPoolBean.kwParam = new CarPoolBean.KwParamBean();
        selectCarPoolBean.kwParam.carBrandImgUrl = imgUrl;
        et_car_num.setText(carNum);
        et_car_num.setSelection(carNum.length());
        btn_creat.performClick();
    }

    public void setCarNum(String carNum) {
        et_car_num.setText(carNum);
        et_car_num.setSelection(carNum.length());
        rl_load.setVisibility(View.VISIBLE);
    }

    @SuppressLint("StringFormatInvalid")
    public void setCarInfo(ValidCarBean numBean) {
        //接口成功后
        selectCarPoolBean = null;//避免第二次存数据存不进去
        rl_load.setVisibility(View.GONE);
        if(numBean == null){
            return;
        }
        this.carId = carId;
        boolean exist = numBean.isExist();
        if (!exist) {
            receiveBaseId = numBean.getReceiveBaseId();
            status = (receiveBaseId == 0) ? 0 : 1;
            if (receiveBaseId != 0 && X3Utils.isFastClick()) {

                startToNotFinishReceive(receiveBaseId);
                return;
            }
            iOnClickBtn(status, et_car_num.getText().toString(), receiveBaseId);
        } else {

            receiveBaseId = numBean.getReceiveBaseId();
            status = (receiveBaseId != 0) ? 2 : 0;
            Log.e("info_","X3Utils.isFastClick() = " + X3Utils.isFastClick());
            if (receiveBaseId != 0 && X3Utils.isFastClick()) {
                X3RouterCenter.startReceiveOrder(receiveBaseId,0,false,false);
                finish();
                overridePendingTransition(0, R.anim.activity_exit);
                return;
            }
            X3PickUpListDialog pickUpListDialog = new X3PickUpListDialog(this);
            pickUpListDialog.show();
            pickUpListDialog.changeData(numBean,et_car_num.getText().toString().trim());
            pickUpListDialog.setIonClickCreate(new X3PickUpListDialog.IonClickCreate() {
                @Override
                public void ionclickcheck(long receiveBaseId) {
                    if (!X3Utils.isFastClick()) {
                        return;
                    }
                    startToNotFinishReceive(receiveBaseId);
                    finish();
                    overridePendingTransition(0, R.anim.activity_exit);
                }

                @Override
                public void ionClickCreate(int status, String carNum, long receiveBaseId) {
                    iOnClickBtn(status, et_car_num.getText().toString(), receiveBaseId);
                }

                @Override
                public void iOnClickHeader(long carOwnid) {
                    X3CreateServiceActivity.this.iOnClickHeader(carOwnid);
                }

                @Override
                public void iOnClickCar(long carId) {
                    X3CreateServiceActivity.this.iOnClickCar(carId);
                }
            });
        }
    }

    /**
     * 跳转到未完成的接车单页面
     */
    private void startToNotFinishReceive(long receiveBaseId) {
        Intent intent = new Intent(this, X3ServiceInfoActivity.class);
        intent.putExtra("receiveBaseId",receiveBaseId);
        intent.putExtra("title","订单支付详情页");
        startActivity(intent);
    }

    private Handler mHandler = new Handler();

    private Runnable runnable = () -> showWorkInput();
    private Runnable runnable2 = () -> adjustBottom();

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (keyPop != null && keyPop.isShowing()) {
            keyPop.dismiss();
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        if (homeCarDialog != null) {
            homeCarDialog.dismiss();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (homeCarDialog != null) {
            homeCarDialog.resetEtCarName();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (homeCarDialog != null) {
            homeCarDialog.resetEtCarName();
        }
    }

    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("接车单车牌号弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("接车单车牌号弹窗");
    }

    @Override
    public void getStoreIconListSuccess(List<String> dataList) {
        if(X3StringUtils.isListEmpty(dataList)){
            initData();
            return;
        }

        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
        if(carMemberBean == null){
            tv_recent.setVisibility(View.GONE);
        }else {
            if(X3StringUtils.isListEmpty(carMemberBean.getList())){
                tv_recent.setVisibility(View.GONE);
            }else {
                List<LiveSelectCarBean> carList = carMemberBean.getList();
                for (int i = 0; i < carList.size(); i++){
                    if(!X3StringUtils.isEmpty(dataList.get(i))){
                        carList.get(i).carBrandImgUrl = dataList.get(i);
                    }
                }
                carMemberBean.setCarName(mobile + "车牌号");
                carMemberBean.setList(carList);
                DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                CarMemberBean carBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
                ll_recent.setVisibility(View.VISIBLE);
                tv_search.setVisibility(View.VISIBLE);
                tv_recent.setVisibility(View.VISIBLE);
                rlv_number.setVisibility(View.VISIBLE);
                licenseNumberAdapter.setData(carBean.getList());
            }
        }
    }

    @Override
    public void getStoreCarNumReceiveSuccess(List<LiveSelectCarBean> datalist) {
        dataList = datalist;
        //刷新数据
        if(licenseNumberAdapter == null){
            return;
        }
        ll_recent.setVisibility(View.VISIBLE);
        licenseNumberAdapter.setData(datalist);
        rlv_number.setVisibility(View.VISIBLE);
        tv_recent.setVisibility(View.GONE);
        tv_search.setVisibility(View.VISIBLE);
    }

    @Override
    public void listStoreAllCarSuccess(CarPoolMainBean carPoolMainBean) {
        if (carPoolMainBean == null) {
            X3ToastUtils.showMessage(getString(R.string.x3_home_no_select));
            List<CarModelSelectBean> selectLists = new ArrayList<>();
            carPoolDailog.changeData(getString(R.string.car_pool), new ArrayList<>(), selectLists);
            return;
        }
        if (X3StringUtils.isListEmpty(carPoolMainBean.list)) {
            X3ToastUtils.showMessage(this.getString(R.string.x3_home_no_select));
            List<CarModelSelectBean> selectLists = new ArrayList<>();
            carPoolDailog.changeData(getString(R.string.car_pool), carPoolMainBean.list, selectLists);
            return;
        } else {
            if (carPoolDailog != null) {
                List<CarModelSelectBean> selectLists = new ArrayList<>();
                carPoolDailog.changeData(getString(R.string.car_pool), carPoolMainBean.list, selectLists);
            }
        }
    }

    @Override
    public void getCarInfo(ValidCarBean searchNumBean) {

        if (carDriLicBean != null){
            //把行驶证识别到的信息设置上去。
            if (!X3StringUtils.isEmpty(carDriLicBean.carVin)){
                searchNumBean.setVin(carDriLicBean.carVin);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.carNum)){
                searchNumBean.setCarNum(carDriLicBean.carNum);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.registrationDate)){
                searchNumBean.setRegistrationDate(carDriLicBean.registrationDate);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.lastName)){
                searchNumBean.setLastName(carDriLicBean.lastName);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.firstName)){
                searchNumBean.setFirstName(carDriLicBean.firstName);
            }
            //
        }
        setCarInfo(searchNumBean);
    }

    /**
     * 识别车牌号
     */
    private void iOnClikCamera() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            if (!X3Utils.isFastClick()) {
                                return;
                            }
                            String path = X3FileUtils.getStoragePath(X3CreateServiceActivity.this, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg";
                            Intent intent = new Intent(X3CreateServiceActivity.this, X3HomeCameraActivity.class);
                            intent.putExtra("path", path);
                            intent.putExtra("title", getString(R.string.x3_recognize_car_number));
                            intent.putExtra("type", true);
                            intent.putExtra("isFromCarNum", true);

                            startActivityForResult(intent, CODE_CAMERA_REQUEST);
                        }else {
                            XXPermissions.startPermissionActivity(X3CreateServiceActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3CreateServiceActivity.this,permissions);
                    }
                });
    }

    /**
     * 跳转到车主详情
     * @param carOwnId
     */
    private void iOnClickHeader(long carOwnId) {
        // 跳转到车主详情页
        if (carOwnId == 0) {
            X3ToastUtils.showMessage(getString(R.string.x3_no_user_detail));
            return;
        }
        if (!X3Utils.isFastClick()) {
            return;
        }
        // 跳转到车主 用户详情页
        Bundle bundle = new Bundle();
        bundle.putString("title","客户详情页");
        bundle.putBoolean("isDark",true);
        bundle.putString("path", X3Constent.HOME_CUSETOM_DETAIL_URL + carOwnId);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
    }


    private void iOnClickCar(long carId) {
        // 跳转到车辆详情页
        if (carId == 0) {
            X3ToastUtils.showMessage(getString(R.string.x3_no_user_detail));
            return;
        }
        if (!X3Utils.isFastClick()) {
            return;
        }
        // 跳转到车辆详情页
        Bundle bundle = new Bundle();
        bundle.putString("title","车辆详情页");
        bundle.putBoolean("isDark",true);
        bundle.putString("path", X3Constent.HOME_CAR_DETAIL_URL + carId);
        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
    }

    /**
     * 点击确定
     * @param status
     * @param carNum
     * @param receiveId
     */
    private void iOnClickBtn(int status, String carNum, long receiveId) {
        this.carNum = carNum;
        switch (status) {
            case 0:
                // 首次到店及非首次到店
                if (mPresenter != null) {
                    mPresenter.saveReceiveBase(carNum);
                }
                break;
            case 1:
                // pc端创建了接车单 但是没有完善车辆信息
                createReceiveSuccess(receiveId, carNum);
                break;
            case 2:
                if (!X3Utils.isFastClick()) {
                    return;
                }
                startToNotFinishReceive(receiveId);
                break;
        }
    }

    /**
     * 创建接车单成功
     * @param receiveId
     * @param carNum
     */
    @Override
    public void createReceiveSuccess(long receiveId, String carNum) {
        setReceiveId(receiveId);
        // 创建接车单成功
        homeCarDialog = new X3BottomHomeCarDialog(this,this);
        homeCarDialog.show();
        homeCarDialog.setReceiveId(receiveId,carNum);
        homeCarDialog.setiOnClick(this);
        //获取接车单数据
        if (mPresenter != null) {
            mPresenter.getReceiveBase(receiveId);
        }
    }

    @Override
    public void getReceiveBase(HomeMainCarBean mainCarBean) {
        this.lastname = mainCarBean.getLastName();
        this.detectionFirstOrNot = mainCarBean.isDetectionFirstOrNot();

        //把行驶证识别到的信息设置上去。
        if (carDriLicBean != null){
            if (!X3StringUtils.isEmpty(carDriLicBean.carVin)){
                mainCarBean.setCarVin(carDriLicBean.carVin);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.carNum)){
                mainCarBean.setCarNum(carDriLicBean.carNum);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.registrationDate)){
                mainCarBean.setCarProductionDate(carDriLicBean.registrationDate + " 00:00:00");
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.lastName)){
                mainCarBean.setLastName(carDriLicBean.lastName);
            }
            if (!X3StringUtils.isEmpty(carDriLicBean.firstName)){
                mainCarBean.setFirstName(carDriLicBean.firstName);
            }
        }
        //

        // TODO 获取当前接车单数据
        if (mainCarBean == null) {
            return;
        }
        if (homeCarDialog != null) {
            homeCarDialog.changeHomeMainData(mainCarBean);
        }

        carDriLicBean = null;
    }

    /*
     * 将时间转换为时间戳
     */
    public String dateToStamp(String s) {
        String res = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }

    @Override
    public void updateReceiveBaseSuccess(UpadateReceBean upadateReceBean) {
        if (homeCarDialog != null) {
            homeCarDialog.resetButton();
        }
        if (upadateReceBean == null) {
            return;
        }
        carId = upadateReceBean.getCarId();
        DeleteFriends deleteFriends = new DeleteFriends("Create_Service_Order");
        EventBus.getDefault().post(deleteFriends);

        /**
         * 第一种：获取头像,如果为空的话，生成图片，上传服务器
         * 第二种：如果在接车单填写的lastname和原有的，说明用户更改了名称，那么需要重新生成图片上传
         */
        if (X3StringUtils.isEmpty(upadateReceBean.getCarOwnerUserImgUrl()) || !upadateReceBean.getLastName().equals(lastname)) {
            //生成图片地址
            String coweUserImg = X3ModifyHeaderView.setName(upadateReceBean.getLastName(),upadateReceBean.getFirstName(), this);
            //如果coweUserImg不为空的话，上传头像
            if (!X3StringUtils.isEmpty(coweUserImg)) {
                //获取七牛接口，将图片上传七牛
                mPresenter.uploadHeaderAws(new File(coweUserImg),upadateReceBean.getCarId());
            }else {
                uploadHeaderSuccess();
            }
        }else {
            uploadHeaderSuccess();
        }

    }

    @Override
    public void uploadHeaderSuccess() {
        EventBus.getDefault().post("UPDATE_START_ORDER");
        startToGroundPush();
    }

    private void startToGroundPush() {
        if (!X3Utils.isFastClick()) {
            return;
        }
        if (homeCarDialog != null) {
            homeCarDialog.dismiss();
        }
        if (viewProxy != null) {
            viewProxy.hideLoading();
        }
        X3ToastUtils.showMessage(getString(R.string.x3_create_receive_success));

        X3RouterCenter.startReceiveOrder(receiveBaseId,carId, detectionFirstOrNot,true);
        finish();
        overridePendingTransition(0, R.anim.activity_exit);
    }

    @Override
    public void updateReceiveBaseFailed() {
        if (homeCarDialog != null) {
            homeCarDialog.resetButton();
        }
    }

    @Override
    public void iOnClikCameraVin() {

        X3RouterCenter.startVin(this);
    }

    @Override
    public void iOnClickCarBtnNext(CarSelectBean selectBean) {
        this.selectBean = selectBean;
        if (viewProxy != null) {
            viewProxy.showLoading("");
        }
        if (mPresenter != null) {
            // 创建接车单，更新车主信息
            mPresenter.updateReceiveCar(selectBean, carNum);
        }
    }

    @Override
    public void iOnClickDismiss(long receiveId) {
        if (mPresenter != null && receiveId != 0) {
            mPresenter.deleteReceiveCar(receiveId);
            this.receiveBaseId = 0;
        }
    }

    @Override
    public void iOnCancelCurrentPage() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null) {
            return;
        }

        switch (requestCode) {
            case CODE_CAMERA_REQUEST:
                String filePath = data.getStringExtra("path");
                isDrivingLicense = data.getBooleanExtra("isDrivingLicense",false);
                this.showLoading("");
                Luban.with(this)
                        .load(filePath)
                        .ignoreBy(100)
                        .setTargetDir(X3FileUtils.getStoragePath(this, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                        .filter(path -> !(TextUtils.isEmpty(filePath) || filePath.toLowerCase().endsWith(".gif")))
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {
                                requestPicData(file);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }
                        }).launch();

                break;
            case CODE_CAMERA_VIN_REQUEST:

                if (homeCarDialog == null) {
                    return;
                }
                if(X3Constent.isChina()){
                    String vinResult = data.getStringExtra("vinResult");
                    System.out.println("识别vin码"+vinResult);
                    homeCarDialog.setVin(vinResult);
                }else {
                    String vinPath = data.getStringExtra("path");
                    Luban.with(this)
                            .load(vinPath)
                            .ignoreBy(100)
                            .setTargetDir(X3FileUtils.getStoragePath(this, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH))
                            .filter(path -> !(TextUtils.isEmpty(vinPath) || vinPath.toLowerCase().endsWith(".gif")))
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {

                                }

                                @Override
                                public void onSuccess(File file) {
                                    if (mPresenter != null) {
                                        showTips();
                                        mPresenter.requestVin(file);
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {

                                }
                            }).launch();
                }

                break;
        }
    }

    private void requestPicData(File file){
        if (mPresenter != null) {
            if (isDrivingLicense) {
                mPresenter.requestDriLicNum(file);
            } else {
                mPresenter.requestCarNum(file);
            }
        }
    }

    private void showTips(){
        if (shareDialog == null) {
            shareDialog = new X3TipsDialog(this,getString(R.string.x3_maintain_vin_analysising));
        }
        shareDialog.show();
    }

    private void hideTip(){
        if (shareDialog != null) {
            shareDialog.dismiss();
        }
    }

    @Override
    public void getCarNum(String carNum) {
        this.hideLoading();
        if (X3StringUtils.isEmpty(carNum)) {
            X3ToastUtils.showMessage(getString(R.string.x3_no_recognize_car_number));
            return;
        }
        this.carNum = carNum;
        et_car_num.setText(carNum);
        if (mPresenter != null) {
            mPresenter.searchByCarNum(carNum);
        }
    }

    @Override
    public void onGetDriLicNum(CarDriLicBean bean) {
        this.hideLoading();
        if (bean == null){
            return;
        }
        if (X3StringUtils.isEmpty(bean.carNum)) {
            X3ToastUtils.showMessage(getString(R.string.x3_car_dri_error_tips));
            return;
        }
        this.carNum = bean.carNum;
        carDriLicBean = bean;
        et_car_num.setText(carNum);
        if (mPresenter != null) {
            mPresenter.searchByCarNum(carNum);
        }
    }

    @Override
    public void getVin(String vin) {
        this.hideLoading();
        hideTip();
        if (homeCarDialog == null) {
            return;
        }
        homeCarDialog.setVin(vin);
    }

    @Override
    public void getVinFail(String error) {
        hideTip();
    }

    /**
     * 上传车辆切割图成功
     * @param colorBean
     */
    @Override
    public void uploadCarPicSuccess(CarPicAndColorBean colorBean) {
        if (colorBean == null) {
            X3ToastUtils.showMessage(getString(R.string.x3_car_cut_fail));
            if (homeCarDialog != null) {
                homeCarDialog.uploadCarCutSuccess(null);
            }
        }else {
            if (homeCarDialog != null) {
                homeCarDialog.uploadCarCutSuccess(colorBean);
            }
        }
    }

    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(DeleteFriends deleteFriends) {
        String type = deleteFriends.getType();
        if ("CarCut".equals(type)){
            // 这里是首页创建接车单修改缩略图
            Log.e("SSSS","首页创建梭路图");
            String imgPath = deleteFriends.getImgPath();
            long carId = deleteFriends.getCarId();
            String carNum = deleteFriends.getCarNum();

            if (homeCarDialog != null) {
                X3ToastUtils.showMessage(getString(R.string.x3_upload_car_cut_notice));
                homeCarDialog.changeLastCarCut(imgPath + "");
                // 上传首页创建的缩略图 切割
                if (mPresenter != null) {
                    mPresenter.uploadCarPic(carId,imgPath,carNum);
                }
            }
        }
    }

}